package workforecast

import org.springframework.dao.DataIntegrityViolationException

class ForecastController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
		User user = User.get(session.getAttribute("me"))
		
		def forecastList
		if (user.role.name.equals("Consultant")) {
			forecastList = Forecast.findAllWhere(user: user)
		} else {
			params.max = Math.min(max ?: 10, 100)
			forecastList = Forecast.list(params)
		}

        [forecastInstanceList: forecastList, forecastInstanceTotal: Forecast.count()]
    }

	public Forecast getLatestForecast() {
		def userInstance = User.get(session.getAttribute("me"))
		def forecasts = Forecast.findAllWhere(user: userInstance)

		int latestDate = 0		// Date = YYYYWW
		def latestForecast
		
		// Search latest forecast by comparing end dates
		for (int i = 0; i < forecasts.size(); i++) {
			int date = forecasts.get(i).endYear * 100 + forecasts.get(i).endWeek
			if (date > latestDate) {
				latestDate = forecasts.get(i).endYear * 100 + forecasts.get(i).endWeek
				latestForecast = forecasts.get(i)
			}
		}
		
		latestForecast
	}
	
    def create() {

		// Copy activities from previous forecast
		def newForecast = new Forecast(params)
		def latestForecast = getLatestForecast()
		
		GregorianCalendar calendar = new GregorianCalendar();
		
		if (latestForecast != null) {
			newForecast.activities = latestForecast.activities
			
			// Just for show past activities
			Iterator it = newForecast.activities.iterator()
			while (it.hasNext()) {
				Activity activity = it.next()
				activity.forecast = null
				activity.workloadEstimation = 0
			}
			
			// Set week number
			if ((latestForecast.endWeek + 1) <= 52) {
				newForecast.startWeek = latestForecast.endWeek + 1
				newForecast.endWeek = newForecast.startWeek 
				
				newForecast.startYear = latestForecast.endYear
				newForecast.endYear = newForecast.startYear
				
	    	} else {
				newForecast.startWeek = 1
				newForecast.endWeek = newForecast.startWeek
				
				newForecast.startYear = calendar.get(Calendar.YEAR) + 1	// Next year
				newForecast.endYear = newForecast.startYear
			}
			
		} else {
			newForecast.startWeek = calendar.get(Calendar.WEEK_OF_YEAR) + 1 // Next week
			newForecast.startYear = calendar.get(Calendar.YEAR)				// Current year
			newForecast.endWeek = newForecast.startWeek
			newForecast.endYear = newForecast.startYear
		}
		
		// Set user to current user
		newForecast.user = User.get(session.getAttribute("me"));
		
        [forecastInstance: newForecast]
    }

    def save() {
		// Copy activities from previous forecast
		def forecastInstance = new Forecast(params)
		def latestForecast = getLatestForecast()
		
		// Set user to current user
		forecastInstance.user = User.get(session.getAttribute("me"));
		
        if (!forecastInstance.save(flush: true)) {
            render(view: "create", model: [forecastInstance: forecastInstance])
            return
        }

		// Copy activities
		if (latestForecast != null) {
			Iterator it = latestForecast.activities.iterator()
			while (it.hasNext()) {
				Activity activity = it.next()
				Activity copiedActivity = new Activity()
				copiedActivity = activity.clone()
				copiedActivity.workloadEstimation = 0
				copiedActivity.forecast = forecastInstance
				copiedActivity.save()
			}	
		}	
		
        flash.message = message(code: 'default.created.message', args: [message(code: 'forecast.label', default: 'Forecast'), forecastInstance.id])
        redirect(action: "show", id: forecastInstance.id)
    }

    def show(Long id) {
        def forecastInstance = Forecast.get(id)
        if (!forecastInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "list")
            return
        }
		
		def it = forecastInstance.activities.iterator()
		int totalWorkload = 0
		while (it.hasNext()) {
			totalWorkload += it.next().workloadEstimation
		}

		if (totalWorkload > 100) {
			flash.warning = message(code: 'Workload is over 100%')
		}
		
        [forecastInstance: forecastInstance]
    }

    def edit(Long id) {
        def forecastInstance = Forecast.get(id)
        if (!forecastInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "list")
            return
        }

        [forecastInstance: forecastInstance]
    }

    def update(Long id, Long version) {
        def forecastInstance = Forecast.get(id)
        if (!forecastInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (forecastInstance.version > version) {
                forecastInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'forecast.label', default: 'Forecast')] as Object[],
                          "Another user has updated this Forecast while you were editing")
                render(view: "edit", model: [forecastInstance: forecastInstance])
                return
            }
        }

        forecastInstance.properties = params

        if (!forecastInstance.save(flush: true)) {
            render(view: "edit", model: [forecastInstance: forecastInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'forecast.label', default: 'Forecast'), forecastInstance.id])
        redirect(action: "show", id: forecastInstance.id)
    }

    def delete(Long id) {
        def forecastInstance = Forecast.get(id)
        if (!forecastInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "list")
            return
        }

        try {
            forecastInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'forecast.label', default: 'Forecast'), id])
            redirect(action: "show", id: id)
        }
    }
}
